\section{Usage}
The python version should be called like this
\begin{pycode}
from matrix2latex import *
matrix=[]
filename=None
environment = list()
keywords = dict()
\end{pycode}
\begin{pygments}{python}
matrix2latex(matrix, filename, *environment, **keywords)
\end{pygments}

  
\subsection{matrix}
\begin{itemize}
\item[Python:] A numpy matrix, a pandas DataFrame/Series or a (nested) list. 
  Note: these are all converted to a nested list internally for compatibility.
\item[Matlab:] Matrix or cell array.
\end{itemize}
\subsection{Filename}
  File to place output, extension .tex is added automatically. File can be included in a LaTeX
  document by \verb!\input{filename}!. Output will always be returned in a string. If filename is None
  not a string or empty string it is ignored.
  
\subsection{*environments}
  Use 
\pygment{python}{matrix2latex(m, None, "align*", "pmatrix", ...)} for matrix.
  This will give
  \begin{align*}
    \begin{pmatrix}
      1 & 2 \\
      3 & 4
    \end{pmatrix}
  \end{align*}
  Use 
\pygment{python}{matrix2latex(m, "test", "table", "center", "tabular" ...)} for table.
  Table is default so given no arguments: table, center and tabular will be used.
  The above command is then equivalent to \\
\pygment{python}{matrix2latex(m, "test", ...)}

The above commands looks a bit differently in matlab, since we must specify
that we want to change the environment.
\begin{pygments}{matlab}
matrix2latex(m, None, 'environment', {'align*', 'pmatrix'}, ...)
matrix2latex(m, 'test', 'environment', {'table', 'center', 'tabular'} ...)
matrix2latex(m, 'test', ...)
\end{pygments}

\subsubsection{Example}
\begin{pyblock}
from matrix2latex import matrix2latex
m = [[1, 1], [2, 4], [3, 9]] # python nested list
t = matrix2latex(m)
print(t)
\end{pyblock}
\begin{pygments}{tex}
\begin{center}
  \begin{tabular}{cc}
    \toprule
    $1$ & $1$\\
    $2$ & $4$\\
    $3$ & $9$\\
    \bottomrule
  \end{tabular}
\end{center}
\end{table}
\end{pygments}
\py{t}

\subsection{**keywords}
\subsubsection{headerRow}
A row at the top used to label the columns.
Must be a list of strings.
Using the same example from above we can add row labels
\begin{pyblock}
hr = ['$x$', '$x^2$']
t = matrix2latex(m, headerRow=hr)
\end{pyblock}

Which in matlab looks like this (note that cell array must be used for
declaring the header row)
\begin{pygments}{matlab}
hr = {'$x$', '$x^2$'};
t = matrix2latex(m, 'headerRow', hr);
\end{pygments}
\py{t}

The python version currently supports header rows spanning multiple columns (using \pygment{latex}{\multicolumn}), this
is done by repeating the header info. It also supports multiple rows 
by using a nested list.
\begin{pycode}[multi]
from matrix2latex import matrix2latex
\end{pycode}
\begin{pyblock}[multi]
hr = [['Item', 'Item', ''],
      ['Animal', 'Description', 'Price (\$)']]
t = [['Gnat', 'per gram', 13.65],
     ['', 'each',  0.01],
     ['Gnu', 'stuffed', 92.50],
     ['Emu', 'stuffed', 33.33],
     ['Armadillo', 'frozen', 8.99]]
t = matrix2latex(t, headerRow = hr, alignment='@{}llr@{}')
\end{pyblock}
\py[multi]{t}
To avoid this behavior ensure each consecutive item is unique, for instance:
\pygment{python}{['Item', 'Item ', '']}
(note the space after the second item).

\subsubsection{headerColumn}
    A column used to label the rows.
    Must be a list of strings
\subsubsection{transpose}
Flips the table around in case you messed up. Equivalent to
matrix2latex(m.H, ...)
if m is a numpy matrix.
Note that \pygment{python}{headerColumn} is used in the example.
\begin{pyblock}
t = matrix2latex(m, headerColumn=hr, transpose=True)
\end{pyblock}
\py{t}

\subsubsection{caption}
Use to define a caption for your table.
Inserts \pygment{python}{\caption} after \pygment{python}{\begin{center}},
note that without the center environment the caption is currently ignored.
Always use informative captions!
\begin{pyblock}
t = matrix2latex(m, headerRow=hr,
                 caption='Nice table!')
\end{pyblock}
\py{t}

\subsubsection{label}
Used to insert \verb!\label{tab:...}! after \verb!\end{tabular}!
Default is filename without extension.

We can use \pygment{python}{label='niceTable'} but if we save it to file
the default label is the filename, so:
\begin{pyblock}
matrix2latex(m, 'niceTable', headerRow=hr, 
                 caption='Nice table!')
\end{pyblock}
can be referenced by \verb!\ref{tab:niceTable}!. Table \ref{tab:niceTable}
was included in latex by \verb!\input{niceTable}!.
\input{niceTable}

\subsubsection{format}
Printf syntax format, e.g. \pygment{python}{$%.2f$}. Default is \pygment{python}{$%g$}.
  This format is then used for all the elements in the table.
Using numpy creating tables for common mathematical expressions are easy:
\begin{pyblock}
import numpy as np
m = np.zeros((3, 2))
m[:, 0] = np.arange(1, 3+1)
m[:, 1] = 1./m[:, 0]

hr = ['$x$', '$1/x$']
t = matrix2latex(m, headerRow=hr,
                 format='%.2f')
\end{pyblock}
\py{t}

\subsubsection{formatColumn}
A list of printf-syntax formats, e.g. \pygment{python}{['$%.2f$', '$%g$']}
Must be of same length as the number of columns.
Format i is then used for column i.
This is useful if some of your data should be printed with more significant figures
than other parts, for instance in the example above $x$ are integers and using
$d$ is more appropriate.
\begin{pyblock}
fc = ['$%d$', '$%.2f$']
t = matrix2latex(m, headerRow=hr, formatColumn=fc)
\end{pyblock}
\py{t}

You could use the format option to add units to you numbers, so for instance
visualizing ohms law
\begin{pyblock}
m2 = np.zeros((3, 2))
R = 50. # ohm
m2[:, 0] = np.arange(1, 3+1)
m2[:, 1] = m[:, 0]/R
c = r'Current through $%g \Omega$ resistor' % R
hr = ['$V$', '$I=V/R$']
t = matrix2latex(m2, 'table_ohm', headerRow=hr,
                 formatColumn=['$%d V$', '$%.2f A$'],
                 caption=c)
\end{pyblock}
\input{table_ohm}

This is however not the recommend way to give units, since they should
be given in the header, see tabel \ref{tab:table_ohm2}.
\begin{pyblock}
hr = ['$V$ [V]', '$I=V/R$ [A]']
t = matrix2latex(m2, 'table_ohm2', headerRow=hr,
                 formatColumn=['$%d$', '$%.2f$'],
                 caption=c)
\end{pyblock}
\input{table_ohm2}

\subsubsection{alignment}
Used as an option when tabular is given as enviroment.
\verb!\begin{tabular}{alignment}!
A latex alignment like c, l or r.
Can be given either as one per column e.g. ``ccc''.
Or if only a single character is given e.g. ``c'',
it will produce the correct amount depending on the number of columns.
Default is ``c'', if you use \pygment{python}{headerColumn} it will always use
``r'' as the alignment for that column.
\begin{pyblock}
t = matrix2latex(m, alignment='rl')
\end{pyblock}
\py{t}

But what if I want vertical rules in my table? Well, this package is built
on top of booktabs for publication ready tables and the booktabs documentation clearly
states ``Never, ever use vertical rule''. But as long as you are not publishing your table,
you could simply use
\begin{pyblock}
t = matrix2latex(m, alignment='|r||c|')
\end{pyblock}
\py{t}

There is some error checking on the alignment but not much, it simply counts the number
of c, l and r in the alignment. All other characters are ignored.

\subsubsection{position}
Used for the table environment to specify the optional parameter ``position specifier''
Default is \pygment{python}{'[' + 'htp' + ']'}

If you want to place your table manually, do not use the table environment.

\subsubsection{General considerations}
Note that many of these options only has an effect when typesetting a table,
if the correct environment is not given the arguments are simply ignored.
To give an example of a very useless function call
\begin{pyblock}
t1 = matrix2latex(m, None, "align*", "pmatrix",
                 alignment='rc',
                 caption='hello world',
                 label='test')
# produces the exact same thing as
t2 = matrix2latex(m, None, "align*", "pmatrix")
assert t1 == t2
\end{pyblock}
\py{t1}
The scary thing is that \pygment{python}{headerColumn} actually works when creating a matrix,
it just looks a bit wierd.

The options presented by this program represents what I need when creating a table,
if you need a more sophisticated table you must either change the python code
(feel free to submit a patch), manually adjust the output afterwards
or adjust the input (remember that the input can be a nested list of strings).
\url{http://en.wikibooks.org/wiki/LaTeX/Tables} gives an excellent overview
of some advanced table techniques.

The booktabs.pdf documentation is an excellent guide to proper table creation,
matrix2latex does not incorporate all the features of this package (yet).

\subsection{Compatibility with other packages}
Bellow support for the python package Pandas and the latex package siunitx will be outlined.
\subsubsection{Pandas support (a python package)}
Some preliminary support for Pandas\footnote{\url{http://pandas.pydata.org/}}
is available, pandas series is shown in table \ref{tab:pd_series}, while
a pandas DataFrame is displayed in table \ref{tab:pd_data_frame}.
\begin{pycode}[pandas]
from matrix2latex import matrix2latex
\end{pycode}
\begin{pyblock}[pandas]
import pandas as pd
s = pd.Series([2, 4, 2, 42, 5], 
              index=['a', 'b', 'c', 'd', 'e'])
t = matrix2latex(s, caption='Pandas Series', 
                 label='pd_series')

m = pd.DataFrame([[1, 1], [2, 4], [3, 9]], 
                 index=['item1', 'item2', 'item3'],
                 columns=['a', 'b'])
t += matrix2latex(m, caption='Pandas Dataframe',
                  label='pd_data_frame')
\end{pyblock}
\py[pandas]{t}

Matrix2latex automatically detects and uses the \pygment{python}{index}
and \pygment{python}{columns} attributes for 
\pygment{python}{headerColumn} and
\pygment{python}{headerRow} respectively. You can override this behavior by passing
\pygment{python}{headerColumn=None, headerRow=None}.

\subsubsection{siunitx (a latex package)}
\pygment{python}{siunitx} provides support for physical quantities with units
and introduces a new column type called
\pygment{latex}{S} which is supported by matrix2latex.
Note that the dollar signs must be suppressed, so the 
\pygment{python}{format} is changed from the default
\pygment{python}{'$%.2g$'}
to
\pygment{python}{'%.2g'}.
\begin{pycode}[siunitx]
from matrix2latex import matrix2latex
\end{pycode}
\begin{pyblock}[siunitx]
import numpy as np
R1 = 50 # ohm
R2 = 377 # ohm
V = np.array([1, 1.2, 100]) # V
I1 = V/R1 # A
I2 = V/R2
caption = r"""Calculated currents through a
$\SI{%g}{\ohm}$ and $\SI{%g}{\ohm}$
resistor.""" % (R1, R2)
headerRow = [['$V$', r'$V/\SI{%g}{\ohm}$' % R1, r'$V/\SI{%g}{\ohm}$' % R2],
             [r'\si{V}', r'\si{A}', r'\si{A}']]
t = matrix2latex([V, I1, I2], caption=caption, transpose=True,
                 alignment='S', format='%.2g', headerRow=headerRow)
\end{pyblock}
\py[siunitx]{t}
%Both caption and label will do nothing if tabular environment is not used.
% \begin{pycode}
% import sys
% sys.path.append('../')
% \end{pycode}
% \begin{pyblock}
% from matrix2latex import matrix2latex
% from numpy import matrix
% m = matrix("1 2 4;3 4 6") # numpy matrix or
% m = [[1, 2, 4], [3, 4, 6]] # python nested list
% matrix2latex(m, "test", "table", "center", "tabular", format="$%.2f$", alignment="lcr")
% # or since table, center and tabular is default:
% t = matrix2latex(m, format="$%.2f$", alignment="lcr")
% # produces:
% \end{pyblock}
% \py{t}

\section{Usage examples}
The usefulness of a programming interface to create \LaTeX{}
tables becomes apparent when the data is dynamically created by python.
This can be either because you want flexibility with respect to the tables size
or because the table content is somehow created by python.

One day you decide to compare different implementations of the
factorial functions, you start by writing the following file
as \verb!factorial.py!
\begin{pyblock}[factorial]
# built in factorial
from math import factorial as factorialMath

# recursive
def factorialRecursive(n):
    if n == 0:
        return 1
    elif n == 1:
        return n
    else:
        return n*factorialRecursive(n-1)

# sequential
def factorialSequential(n):
    if n == 0:
        return 1
    res = 1
    for k in xrange(2, n+1):
        res *= k
    return res  
\end{pyblock}

The first thing to do is to verify that the three implementations actually give
the same results, for this we simply loop over the different functions and try for
different values of $n$. The result is shown in table \ref{tab:facV}.
\begin{pyblock}[factorial]
from matrix2latex import matrix2latex
N = range(0, 10)
table = list()
for func in (factorialMath,
             factorialRecursive,
             factorialSequential):
    row = list()
    for n in N:
        res = func(n)  # call func
        row.append(res)# append result to row
    table.append(row)  # append row to table

# row labels
rl = ['$n$', 'Built-in', 'Recursive', 'Sequential']
caption = '''Vertifying that the different factorial
implementations gives the same results'''
matrix2latex(table, 'facV', caption=caption,
             headerColumn=N, headerRow=rl,
             alignment='r', transpose=True)  
\end{pyblock}
\input{facV}

What we really wanted to do was to
compare the speed of the different implementations. To do this
we use the python package timeit, shown bellow. The speed comparision is given in table \ref{tab:facT}.
\begin{pyblock}[factorial]
import timeit
table = list()
for func in ('factorialMath',
             'factorialRecursive',
             'factorialSequential'):
    row = list()
    for n in N:
        statement = 'factorial.{func}({n})'.format(func=func,
                                                   n=n)
        setup = 'import factorial'
        # measure time
        res = timeit.repeat(statement, setup)
        row.append(min(res)) # append result
    table.append(row) # append row to table

rl = ['$n$', 'Built-in [$s$]',
      'Recursive [$s$]', 'Sequential [$s$]']
caption = '''Comparing execution time for
the different factorial implementations'''
matrix2latex(table, 'facT', caption=caption,
             headerColumn=N, headerRow=rl,
             transpose=True, format='$%.3f$')  
\end{pyblock}
\input{facT}

As an additional example, see \verb!test_compatibility.py! to see how table \ref{tab:compatibleTable}
was created.
